import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { User } from '../api/divide/user/types.gen';

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  setUser: (user: User) => void;
  logout: () => void;
  setLoading: (loading: boolean) => void;
  updateUser: (updates: Partial<User>) => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      isAuthenticated: false,
      isLoading: false,
      setUser: (user) => {
        set({
          user,
          isAuthenticated: true,
          isLoading: false,
        });
      },
      logout: () => {
        set({
          user: null,
          isAuthenticated: false,
          isLoading: false,
        });
        // 清除localStorage中的持久化数据
        if (typeof window !== 'undefined') {
          localStorage.removeItem('auth-storage');
        }
      },
      setLoading: (loading) => 
        set({ isLoading: loading }),
      updateUser: (updates) =>
        set((state) => ({ 
          user: state.user ? { ...state.user, ...updates } : null 
        })),
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({ 
        user: state.user,
        isAuthenticated: state.isAuthenticated 
      }),
    }
  )
);